<template>
  <el-dialog v-model="dialogVisible" title="上传文件" width="500px">
    <div class="upload-area">
      <!-- 添加文件夹上传按钮 -->
      <div class="upload-buttons">
        <input
          type="file"
          ref="fileInput"
          multiple
          style="display: none"
          @change="handleFileChange"
        />
        <input
          type="file"
          ref="folderInput"
          webkitdirectory
          directory
          style="display: none"
          @change="handleFileChange"
        />
        <el-button @click="triggerFileUpload">选择文件</el-button>
        <el-button @click="triggerFolderUpload">选择文件夹</el-button>
      </div>

      <div class="upload-drop-area" 
           @drop.prevent="handleDrop"
           @dragover.prevent
           @dragenter.prevent>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或使用上方按钮选择
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import config from '@/config'
import axios from 'axios'
import { generateNewFilename } from '@/utils/filename'

interface Props {
  modelValue: boolean
  currentPath: string
  files: any[]
}

const props = withDefaults(defineProps<Props>(), {
  currentPath: '/',
  files: () => []
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'upload-success'): void
}>()

// 检查文件名是否存在并生成新名称
const checkAndRenameFile = (file: File, existingFiles: any[]) => {
    const fileExists = existingFiles.some(f => f.name === file.name)
    if (fileExists) {
        const newName = generateNewFilename(file.name, existingFiles)
        return new File([file], newName, {
            type: file.type,
            lastModified: file.lastModified
        })
    }
    return file
}

const fileInput = ref(null)
const folderInput = ref(null)

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const triggerFileUpload = () => {
  console.log('triggerFileUpload')
  fileInput.value.click()
}

const triggerFolderUpload = () => {
  folderInput.value.click()
}

const selectedFiles = ref([])

const handleFileChange = async (event) => {
  const files = Array.from(event.target.files)
  selectedFiles.value = files
  console.log('Files:', files.map(f => ({
    name: f.name,
    path: f.webkitRelativePath
  }))) // 添加日志查看文件路径
  await uploadFiles(files)
  event.target.value = ''
}

const handleDrop = async (event) => {
  const items = event.dataTransfer.items
  const files = []
  
  for (let item of items) {
    if (item.kind === 'file') {
      const entry = item.webkitGetAsEntry()
      if (entry) {
        await traverseFileTree(entry, files)
      }
    }
  }
  
  await uploadFiles(files)
}

const traverseFileTree = async (item, files) => {
  if (item.isFile) {
    const file = await new Promise((resolve) => item.file(resolve))
    file.webkitRelativePath = item.fullPath
    files.push(file)
  } else if (item.isDirectory) {
    const reader = item.createReader()
    const entries = await new Promise((resolve) => {
      reader.readEntries((entries) => resolve(entries))
    })
    for (let entry of entries) {
      await traverseFileTree(entry, files)
    }
  }
}

const uploadFiles = async (files: File[]) => {
  // 收集所有需要创建的目录路径
  const directories = new Set()
  for (let file of files) {
    if (file.webkitRelativePath) {
      const paths = file.webkitRelativePath.split('/')
      paths.pop()
      let currentPath = ''
      for (let dir of paths) {
        currentPath = currentPath ? `${currentPath}/${dir}` : dir
        directories.add(currentPath)
      }
    }
  }

  // 按层级排序目录，确保父目录先创建
  const sortedDirs = Array.from(directories).sort((a, b) => 
    a.split('/').length - b.split('/').length
  )

  // 创建所有目录
  for (let dir of sortedDirs) {
    try {
      const dirName = dir.split('/').pop()
      const parentPath = dir.split('/').slice(0, -1).join('/')
      const fullParentPath = props.currentPath + (parentPath ? parentPath + '/' : '')
      
      console.log('Creating directory:', {
        name: dirName,
        path: fullParentPath
      })

      const response = await axios.post(
        `${config.apiUrl}/file/createFolder`,
        {
          name: dirName,
          path: fullParentPath
        },
        {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        }
      )
      
      if (response.data.code !== 200) {
        ElMessage.error(`创建文件夹 ${dir} 失败: ${response.data.msg}`)
      }
    } catch (error) {
      ElMessage.error(`创建文件夹 ${dir} 失败: ${error.message}`)
    }
  }

  // 上传文件到对应目录
  for (let file of files) {
    if (file.size > 2 * 1024 * 1024 * 1024) {
      ElMessage.error(`文件 ${file.name} 大小超过2GB`)
      continue
    }

    // 构造文件的完整路径
    let uploadPath = props.currentPath
    if (file.webkitRelativePath) {
      const paths = file.webkitRelativePath.split('/')
      paths.pop() // 移除文件名
      uploadPath += paths.join('/')
      if (uploadPath !== '/') {
        uploadPath += '/'
      }
    }

    try {
      // 获取目标目录的文件列表
      const listResponse = await axios.get(
        `${config.apiUrl}/file/list`,
        {
          params: { path: uploadPath },
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        }
      )
      const trashResponse = await axios.get(
        `${config.apiUrl}/file/trash`,  // 假设这是获取回收站文件的API
        {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        }
      )

      const dirFiles = listResponse.data.data.files || []
      const trashFiles = trashResponse.data.data.files || []

      const allFiles = [...dirFiles, ...trashFiles]
      // 检查并重命名文件
      const renamedFile = checkAndRenameFile(file, allFiles)
      const formData = new FormData()
      formData.append('file', renamedFile)
      formData.append('path', uploadPath)

      console.log('Uploading file:', {
        originalName: file.name,
        newName: renamedFile.name,
        path: uploadPath
      })

      const response = await axios.post(
        `${config.apiUrl}/file/upload`,
        formData,
        {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'multipart/form-data'
          }
        }
      )
      console.log('response', response.data)
      if (response.data.code === 200) {
        ElMessage.success(`文件 ${renamedFile.name} 上传成功`)
        
      } else {
        ElMessage.error(response.data.msg || `文件 ${renamedFile.name} 上传失败`)

      }
    } catch (error) {
      ElMessage.error(`文件 ${file.name} 上传失败: ${error.message}`)
    }
  }
  
  console.log('All files uploaded successfully') 
  emit('upload-success')  // 确保调用
  dialogVisible.value = false  // 确保关闭对话框


}
</script>

<style scoped>
.upload-area {
  text-align: center;
}

.upload-buttons {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.upload-drop-area {
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  padding: 40px 0;
  cursor: pointer;
}

.upload-drop-area:hover {
  border-color: #409eff;
}

.el-icon--upload {
  font-size: 48px;
  color: #909399;
  margin-bottom: 10px;
}

.el-upload__text {
  color: #606266;
}
</style>